/*
 * Salesforce programming test.
 * Applicant: Ying Xu
 *
 * Compiled with: g++ (GCC) 4.8.2 20131212 (Red Hat 4.8.2-7) on 64-bit Linux
 *
 * Linux localhost.localdomain 3.12.6-200.fc19.x86_64 #1 SMP Mon Dec 23 16:33:38
 * UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
 */

#include <iostream>
#include <cstdio>
#include <algorithm>
#include "Dependancy.h"

int main(int argc, char *argv[]) {
    if (argc < 2) {
        cout << "Usage: " << argv[0] << " testfile" << endl;
        return -1;
    }

    // read file by re-directing to stdin
    if (freopen(argv[1], "r", stdin) == NULL) {
        cout << "file " << argv[1] << " cannot be opened" << endl;
        return -1;
    }

    string line("");
    DepController controller;
    while (getline(cin, line)) {
        vector<string> params;
        size_t start = 0, pos = 0;
        // split line into tokens divided by spaces
        while ((pos = line.find(' ', start)) != line.npos) {
            if (pos > start) {
                params.push_back(line.substr(start, pos-start));
            }
            start = pos+1;
        }
        // last parameter
        if (start < line.length()) params.push_back(line.substr(start));

        // All empty spaces
        if (params.empty()) continue;

        reverse(params.begin(), params.end());
        // extract command and module name
        string cmd(""),  module("");
        cmd = params[params.size()-1]; params.pop_back();
        if (params.size()) {
            module = params[params.size()-1];
            params.pop_back();
        }

        // print out current cmdline
        cout << line << endl;

        if (cmd == "END") break; // last line
        controller.Exec(cmd, module, params);
    }

    return 0;
}
